import { createRouter, createWebHashHistory } from 'vue-router'
import layout from '../views/layout/index.vue'
import store from '@/store'

const routes = [
  {
    path: '/test',
    component: () => import('@/views/test/index.vue')
  },
  {
    path: '/',
    // name: 'Home',
    component: layout,
    children: [
      {
        path: '/pay',
        component: () => import('@/views/Pay')
      },
      {
        path: '/settlement',
        component: () => import('@/views/Settlement')
      },
      {
        path: '/',
        component: () => import('@/views/Home/index.vue')
      },
      {
        path: '/category/:id',
        component: () => import('@/views/category/index.vue')
      },
      {
        path: '/goods/:id',
        component: () => import('@/views/Goods/index.vue')
      },
      {
        path: '/cart',
        component: () => import('@/views/cart/index.vue')
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/Login/index.vue')
  },
  {
    path: '/login/callback',
    component: () => import('@/views/Login/callback')
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 切换页面的时候自动滚动顶部
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 守卫导航
router.beforeEach((to, from, next) => {
  // 如果用户到路径以'/member'开头，且没用token 的情况下，带原来的地址跳转到登录页面，如果到其他页面，则放行
  if (to.path.startsWith('/member') && !store.state.user.token) {
    next('/login?redirectUrl=' + to.fullPath)
  } else {
    next()
  }
})

export default router
